package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName ApCollectionServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/23 0:03
 * @Version 1.0
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Resource
    private BehaviorFeign behaviorFeign;

    /**
     * @param dto 收藏请求收藏对象
     * @return 保存结果
     * @Description 保存收藏行为
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //根据app用户id查询实体信息
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (ObjectUtils.isEmpty(apBehaviorEntry)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getEntryId())
                .eq(ApCollection::getEntryId, apBehaviorEntry.getId()));

        // 保存收藏
        if (ObjectUtils.isEmpty(apCollection) && dto.getOperation().equals(ApCollection.Operation.COLLECTION.getCode())) {
            apCollection = new ApCollection();
            apCollection.setOperation(dto.getOperation());
            apCollection.setCollectionTime(new Date());
            apCollection.setType(dto.getType());
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setPublishedTime(dto.getPublishedTime());
            save(apCollection);
        } else {
            //4.取消点赞
            apCollection.setOperation(dto.getOperation());
            updateById(apCollection);
        }
        return ResponseResult.okResult();
    }
}
